package com.zd.controller;

import com.github.pagehelper.PageHelper;
import com.zd.config.MinioConfig;
import com.zd.domain.Course;
import com.zd.domain.Result;
import com.zd.domain.User;
import com.zd.mapper.CourseMapper;
import com.zd.service.MinioService;
import com.zd.service.course.CourseService;
import com.zd.utils.CourseIdGeneration;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private MinioService minioService;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private CourseMapper courseMapper;


    /**
     * 查询全部课程（管理员调用）
     * @return
     */
    @CrossOrigin
    @GetMapping
    public Result<List<Course>> courseList() {

        Result<List<Course>> result = new Result<>();
        List<Course> courseList = (List<Course>)redisTemplate.boundValueOps("courseList").get();
        if (courseList == null){
            System.out.println(111);
            List<Course> courses = courseService.courseList();

            if (courses == null) {
                result.setCode(411);
                result.setMsg("暂无数据");
            } else {
                result.setCode(200);
                result.setData(courses);
                result.setMsg("查询成功");
                redisTemplate.boundValueOps("courseList").set(courses,1, TimeUnit.MINUTES);
            }
        }else {
            System.out.println(222);
            result.setCode(200);
            result.setData(courseList);
            result.setMsg("查询成功");
        }
        return result;
    }

    /**
     * 模糊匹配
     *
     * @param courseName
     * @return
     */
    @CrossOrigin
    @GetMapping("findByName")
    public Result<List<Course>> findCourseByName(@RequestParam("courseName") String courseName) {
        List<Course> courseByName = courseService.findCourseByName("%" + courseName + "%");
        Result<List<Course>> result = new Result<>();

        if (courseByName == null) {
            result.setCode(411);
            result.setMsg("暂无数据~~");
        } else {
            result.setCode(200);
            result.setData(courseByName);
            result.setMsg("查询成功！");
        }

        return result;
    }

    /**
     * 修改课程
     *
     * @param course
     * @return
     */
    @CrossOrigin
    @PostMapping("updateCourse")
    public Result updateCourse(@RequestBody Course course) {
        int influenceRows = courseService.updateCourse(course);

        Result<String> result = new Result<>();

        if (influenceRows == 1) {
            result.setCode(200);
            result.setMsg("修改成功~~");
            List<Course> courses = courseService.courseList();
            redisTemplate.boundValueOps("courseList").set(courses,1, TimeUnit.MINUTES);
        } else {
            result.setCode(400);
            result.setData("修改失败");
        }
        return result;

    }

    /**
     * 新增课程
     * @param couCoverFile  封面文件
     * @param vAndBFile   视频文件
     * @param course
     * @return
     */
    @CrossOrigin
    @PostMapping("saveCourse")
    public Result saveCourse(@RequestPart("couCoverFile") MultipartFile couCoverFile,
                             @RequestPart("vAndBFile") MultipartFile vAndBFile,
                             @RequestPart("course") Course course) {
        String coverUrl = null;
        String vAndBUrl = null;

        Result result = new Result();
        if(couCoverFile == null){
            result.setCode(425);
            result.setMsg("封面文件未上传");
        }else if (vAndBFile == null){
            result.setCode(430);
            result.setMsg("视频/电子书文件未上传");
        }else {
            try {
                //封面图片地址
                coverUrl = minioService.uploadFile(minioConfig.getBucketName(),couCoverFile);
                //视频或者电子书地址
                vAndBUrl = minioService.uploadFile(minioConfig.getBucketName(),vAndBFile);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //给课程生成新的课程号
            int courseId = CourseIdGeneration.generateRandom7DigitNumber();

            //创建课程对象封装
            Course addCourse = new Course();
            addCourse.setCourseId(courseId);
            addCourse.setCourseCover(coverUrl);
            addCourse.setCourseName(course.getCourseName());
            addCourse.setCourseDesc(course.getCourseDesc());
            addCourse.setCourseOPrice(course.getCourseOPrice());
            addCourse.setCourseCPrice(course.getCourseCPrice());
            addCourse.setCourseState(course.getCourseState());
            addCourse.setGoodPosition(course.getGoodPosition());
            addCourse.setGoodAddress(vAndBUrl);

            //调用方法增加课程
            int influenceRows = courseService.saveCourse(addCourse);
            if (influenceRows == 1){
                result.setCode(200);
                result.setMsg("新增成功");

                //再去查询一遍已上架的课程，存入redis中
                List<Course> coursesGro = courseMapper.findCoursesGro();
                System.out.println(coursesGro.size());

                redisTemplate.boundValueOps("upCourses").set(coursesGro,1,TimeUnit.MINUTES);
                List<Course> list = (List<Course>)redisTemplate.boundValueOps("upCourses").get();
                System.out.println(list.size());
            }else {
                result.setCode(411);
                result.setMsg("新增失败");
            }
        }
        return result;
    }

    /**
     * 根据课程id查询课程
     *
     * @param courseId
     * @return
     */
    @CrossOrigin
    @GetMapping("findById")
    public Result<Course> findByCourseId(@RequestParam("courseId") int courseId) {

        Course course = courseService.findCourseById(courseId);

        Result<Course> result = new Result<>();
        String redCourse = courseId + "course";
        redisTemplate.delete(redCourse);
        Course getRedCourse = (Course)redisTemplate.boundValueOps(redCourse).get();
        if (getRedCourse == null){
            Course course1 = courseService.findCourseById(courseId);
            if (course1 == null) {
                result.setCode(411);
                result.setMsg("未找到课程号为" + courseId + "的课程");
            } else {
                result.setCode(200);
                result.setData(course1);
                redisTemplate.boundValueOps(redCourse).set(course1,1,TimeUnit.MINUTES);
                result.setMsg("查询成功！~");
            }
        }else {
            result.setCode(200);
            result.setData(getRedCourse);
            result.setMsg("查询成功！~");

        }
        return result;
    }

    /**
     * 查询当前用户已经购买的课程
     *
     * @param userId
     * @return
     */
    @CrossOrigin
    @GetMapping("/myCourses")
    public Result<List<Course>> findMyCourses(@RequestParam("userId") int userId) {
        Result<List<Course>> result = new Result<>();
        String findKey = userId + "courses";

        List<Course> myCourses = (List<Course>)redisTemplate.boundValueOps(findKey).get();
        if (myCourses == null){
            System.out.println(111);
            List goodIds = courseService.findMyCourses(userId);
            List<Course> courseList = new ArrayList<>();

            if (goodIds.size() > 0) {
                for (Object goodId : goodIds) {
                    int courseId = (int) goodId;
                    Course course = courseService.findCourseById(courseId);
                    courseList.add(course);
                }
                result.setCode(200);
                result.setMsg("查询成功！~");
                result.setData(courseList);
                redisTemplate.boundValueOps(findKey).set(courseList);
            } else {
                result.setCode(411);
                result.setMsg("暂无查询数据！~");
            }
        }else {
            System.out.println(222);
            result.setCode(200);
            result.setMsg("查询成功！~");
            result.setData(myCourses);
        }


        return result;
    }

    /**
     * 查询全部已上架的课程的（用户调用）
     * @return
     */
    @CrossOrigin
    @GetMapping("findCoursesGro")
    public Result<List<Course>> findCoursesGro() {
        Result<List<Course>> result = new Result<>();
//        redisTemplate.delete("upCourses");

        List<Course> upCourses = (List<Course>)redisTemplate.boundValueOps("upCourses").get();

        if (upCourses == null){
            List<Course> coursesGro = courseService.findCoursesGro();

            if (coursesGro == null) {
                result.setCode(411);
                result.setMsg("暂无数据~");
            } else {
                result.setCode(200);
                result.setMsg("查询成功");
                result.setData(coursesGro);
                redisTemplate.boundValueOps("upCourses").set(coursesGro,1,TimeUnit.MINUTES);
            }
        }
        else {
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(upCourses);
        }
        return result;
    }

    /**
     * 查询位置在轮播图上并且上架的前4课程
     * @return
     */
    @CrossOrigin
    @GetMapping("/findCoursesCar")
    public Result<List<Course>> findCoursesCar(){
        Result<List<Course>> coursesByCarList = new Result<>();
        List<Course> coursesCar = (List<Course>)redisTemplate.boundValueOps("CoursesCar").get();
        if (coursesCar == null){
            List<Course> coursesCarList = courseService.findCoursesCar();
            if (coursesCarList != null ){
                coursesByCarList.setCode(200);
                coursesByCarList.setMsg("查询成功");
                coursesByCarList.setData(coursesCarList);
                //存入redis
                redisTemplate.boundValueOps("CoursesCar").set(coursesCarList,1,TimeUnit.MINUTES);
            }else {
                coursesByCarList.setCode(411);
                coursesByCarList.setMsg("查询失败");
            }
        }else {
            coursesByCarList.setCode(200);
            coursesByCarList.setMsg("查询成功");
            coursesByCarList.setData(coursesCar);
        }
        return coursesByCarList;

    }

    /**
     * //查询前4条已上架的并且位置在热销的课程
     * @return
     */
    @CrossOrigin
    @GetMapping("/findHotCourses")
    public Result<List<Course>> findHotCourses(){
        Result<List<Course>> coursesByHotList = new Result<>();
        List<Course> HotCourses = (List<Course>)redisTemplate.boundValueOps("HotCourses").get();
        if (HotCourses == null){
            List<Course> coursesHotList = courseService.findHotCourses();
            if (coursesHotList != null ){
                coursesByHotList.setCode(200);
                coursesByHotList.setMsg("查询成功");
                coursesByHotList.setData(coursesHotList);
                //存入redis
                redisTemplate.boundValueOps("HotCourses").set(coursesHotList,1,TimeUnit.MINUTES);
            }else {
                coursesByHotList.setCode(411);
                coursesByHotList.setMsg("查询失败");
            }
        }else {
            coursesByHotList.setCode(200);
            coursesByHotList.setMsg("查询成功");
            coursesByHotList.setData(HotCourses);
        }
        return coursesByHotList;

    }

    /**
     * //查询前4条已上架的并且位置在推荐的课程
     * @return
     */
    @CrossOrigin
    @GetMapping("/findBestCourses")
    public Result<List<Course>> findBestCourses(){
        Result<List<Course>> coursesByBestList = new Result<>();
        List<Course> BestCourses = (List<Course>)redisTemplate.boundValueOps("BestCourses").get();
        if (BestCourses == null){
            List<Course> coursesBestList = courseService.findBestCourses();
            if (coursesBestList != null ){
                coursesByBestList.setCode(200);
                coursesByBestList.setMsg("查询成功");
                coursesByBestList.setData(coursesBestList);
                //存入redis
                redisTemplate.boundValueOps("BestCourses").set(coursesBestList,1,TimeUnit.MINUTES);
            }else {
                coursesByBestList.setCode(411);
                coursesByBestList.setMsg("查询失败");
            }
        }else {
            coursesByBestList.setCode(200);
            coursesByBestList.setMsg("查询成功");
            coursesByBestList.setData(BestCourses);
        }
        return coursesByBestList;

    }

    /**
     * //查询前4条已上架的并且位置在推荐的电子书
     * @return
     */
    @CrossOrigin
    @GetMapping("/findRecCourses")
    public Result<List<Course>> findRecCourses(){
        Result<List<Course>> coursesByRectList = new Result<>();
        List<Course> recCourses = (List<Course>)redisTemplate.boundValueOps("RecCourses").get();
        if (recCourses == null){
            List<Course> coursesRecList = courseService.findRecCourses();
            if (coursesRecList != null ){
                coursesByRectList.setCode(200);
                coursesByRectList.setMsg("查询成功");
                coursesByRectList.setData(coursesRecList);
                //存入redis
                redisTemplate.boundValueOps("RecCourses").set(coursesRecList,1,TimeUnit.MINUTES);
            }else {
                coursesByRectList.setCode(411);
                coursesByRectList.setMsg("查询失败");
            }
        }else {
            coursesByRectList.setCode(200);
            coursesByRectList.setMsg("查询成功");
            coursesByRectList.setData(recCourses);
        }
        return coursesByRectList;
    }

    /**
     * 查询全部已上架的电子书的（用户调用）
     * @return
     */
    @CrossOrigin
    @GetMapping("findAllBooks")
    public Result<List<Course>> findAllBooks() {
        Result<List<Course>> result = new Result<>();
//        redisTemplate.delete("upCourses");

        List<Course> upBookCourses = (List<Course>)redisTemplate.boundValueOps("upBookCourses").get();

        if (upBookCourses == null){
            List<Course> booksGro = courseService.findAllBooks();

            if (booksGro == null) {
                result.setCode(411);
                result.setMsg("暂无数据~");
            } else {
                result.setCode(200);
                result.setMsg("查询成功");
                result.setData(booksGro);
                redisTemplate.boundValueOps("upBookCourses").set(booksGro,1,TimeUnit.MINUTES);
            }
        }
        else {
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(upBookCourses);
        }
        return result;
    }

    /**
     * 新增电子书
     * @param bookCoverFile  封面文件
     * @param bookFile   电子书文件
     * @param course
     * @return
     */
    @CrossOrigin
    @PostMapping("saveBook")
    public Result saveBook(@RequestPart("bookCoverFile") MultipartFile bookCoverFile,
                             @RequestPart("bookFile") MultipartFile bookFile,
                             @RequestPart("course") Course course) {
        String coverUrl = null;
        String bookUrl = null;

        Result result = new Result();
        if(bookCoverFile == null){
            result.setCode(425);
            result.setMsg("封面文件未上传");
        }else if (bookFile == null){
            result.setCode(430);
            result.setMsg("电子书文件未上传");
        }else {
            try {
                //封面图片地址
                coverUrl = minioService.uploadFile(minioConfig.getBucketName(),bookCoverFile);
                //电子书地址
                bookUrl = minioService.uploadFile(minioConfig.getBucketName(),bookFile);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //给电子书课程生成新的课程号
            int courseId = CourseIdGeneration.generateRandom7DigitNumber();

            //创建课程对象封装
            Course addCourse = new Course();
            addCourse.setCourseId(courseId);
            addCourse.setCourseCover(coverUrl);
            addCourse.setCourseName(course.getCourseName());
            addCourse.setCourseDesc(course.getCourseDesc());
            addCourse.setCourseOPrice(course.getCourseOPrice());
            addCourse.setCourseCPrice(course.getCourseCPrice());
            addCourse.setCourseState(course.getCourseState());
            addCourse.setGoodPosition(course.getGoodPosition());
            addCourse.setGoodAddress(bookUrl);

            //调用方法增加电子书课程
            int influenceRows = courseService.saveBook(addCourse);
            if (influenceRows == 1){
                result.setCode(200);
                result.setMsg("新增成功");

                //再去查询一遍已上架的电子书，存入redis中
                List<Course> booksGro = courseMapper.findAllBooks();
                System.out.println(booksGro.size());

                redisTemplate.boundValueOps("upBookCourses").set(booksGro,1,TimeUnit.MINUTES);
            }else {
                result.setCode(411);
                result.setMsg("新增失败");
            }
        }
        return result;
    }

    /**
     * 查询用户的学习记录
     * @param userId
     * @return
     */
    @CrossOrigin
    @GetMapping("/learnRecordByUserId")
    public Result<List<Course>> learnRecordByUserId(@RequestParam("userId") int userId){
        Result<List<Course>> result = new Result<>();
        List<Course> courses = courseService.learnRecordByUserId(userId);
        for (Course course : courses) {
            double currentTime = Double.parseDouble(course.getGoodState().getCurrentTime());
            double totalTime = Double.parseDouble(course.getGoodState().getTotalTime());
            double percentage = (currentTime / totalTime) * 100;
            String formattedRatio = String.format("%.1f", percentage);
            course.getGoodState().setWatchProgress(formattedRatio);
        }
        if (courses.size() > 0){
            result.setCode(200);
            result.setMsg("查找成功");
            result.setData(courses);
        }else {
            result.setCode(244);
            result.setMsg("暂无学习记录");
        }

        return result;
    }

}
